function nav_template(){/*
<a class="btn btn-primary btn{appid}" href="./show-app.php?appid={appid}" title="{des}">
  {name}
</a>
*/}

function search_app_template(){/*
<div><a class="btn btn-primary btn{appid}" style="color:white;text-align:left;width:200px;word-wrap:break-word; word-break:break-all;"
  href="./show-app.php?appid={appid}" target="_blank" title="{des}">
  {name}
  <p text-muted>{des}</p>
</a></div>
*/}

function app_template(){/*
<div class=" col-xs-12 col-sm-4 col-md-3 col-lg-3">
<div class="panel panel-primary skin{skin}">
  <div class="panel-heading">
    <h3 class="panel-title"><a href="./show-app.php?appid={appid}" target="_blank" title="{des}">
      {name}<span class="lang-shortcut">快捷键</span>
    </a></h3>
  </div>
  <div class="panel-body" style="height:300px;overflow:hidden">
    <p>{des}</p>
    <a class="pull-right" href="./show-app.php?appid={appid}" title="{des}" target="_blank">
    <img style='max-width:96px;_width:expression(this.width > 96 ? "96px" : this.width);' src="{logo}" />
    </a>
  </div>
  <div class="panel-footer text-right">
      <a href="export.php?&appid={appid}" target="_blank"
        class="lang-export edit-item">导出</a>
      <a href="add-item.php?appid={appid}" target="_blank"
        class="lang-add add-item">添加</a>
      <a href="edit-app.php?appid={appid}" target="_blank"
        class="lang-edit edit-item">编辑</a>
      <a class="lang-proceed btn btn-success" href="./show-app.php?appid={appid}" target="_blank">前往</a>
  </div>
</div>
</div>
*/}


function add_app_template(){/*
<div class=" col-xs-12 col-sm-4 col-md-3 col-lg-3">
<div class="panel panel-primary skin{skin}">
  <div class="panel-heading">
    <h3 class="panel-title"><a href="./add-app.php" target="_blank" title="{des}">
      {name}
    </a></h3>
  </div>
  <div class="panel-body" style="height:300px;overflow:hidden">
    <h4 class="text-center">{des}</h4>
    <p class="text-center"><a href="./add-app.php" title="{des}" target="_blank">
    <img style='max-width:96px;_width:expression(this.width > 96 ? "96px" : this.width);' src="{logo}" />
    </a></p>
  </div>
  <div class="panel-footer text-right"> 
    <a class="lang-proceed-add btn btn-success" href="./add-app.php" target="_blank">前往添加</a>
  </div>
</div>
</div>
*/}

function is_matched(key, data){
  var tmp =data['name'].toLowerCase();
  var pkey = data['shortcut'];
  var lpkey = pkey.toLowerCase();
  if((tmp.localeCompare(key) == 0)
    || tmp.indexOf(key) != -1
    || (data.pinyin.indexOf(key) != -1)
    || lpkey.indexOf(key) != -1
    || (pkey.indexOf(key) != -1)){
    return true;
  }
  return false;
}



function is_app_matched(key, data){
  var tmp =data['name'].toLowerCase();
  var pkey = data['des'];
  var lpkey = pkey.toLowerCase();
  if((tmp.localeCompare(key) == 0)
    || tmp.indexOf(key) != -1
    || (data.pinyin.indexOf(key) != -1)
    || lpkey.indexOf(key) != -1
    || (pkey.indexOf(key) != -1)){
    return true;
  }
  return false;
}

//搜索结果
function search_data(key)
{
  $("#search-result").html("正在搜索中...")
  key =$.trim(key).toLowerCase();
  if(key == "") return;
  if(key[0]!='范') key = '范' + key;
  var u = 'query.php?op=by-name&name='+key;
  $.ajax(
    {
      url:u,
      dataType:"json",
      async:true,
      success : function(msg, textStatus) { 

        if(msg.code){
          show_msg("#search-result", "未找到结果！"+"("+msg.code+msg.msg+")");
          return;
        }

        var s ="";
        var template_item = hereDoc(search_template);
        var count = 0;
        var content = "";


        var data_list = msg;
        for(var i in data_list){
          var data=data_list[i]; 
          data.i = count + 1;
          var s = nano(template_item, data);
          content += s;
          count += 1;
        }
        content = '<table class="table table-striped">'+content+'</table>'
        $("#search-result").html(content);
    }
  });
}

var all_data = {};
var all_data_list = [];
var gInfo = {};
var gStr = {};

function get_all_callback(appid, d) {
  // 处理多语言的情况
  var all_app = 'all-app';
  var all_shortcut = 'all-shortcut';
  var one_app = 'one-app';
  var comment_count = 'comment-count';
  if (!d[all_app]) all_app = 'all-app-en';
  if (!d[all_shortcut]) all_shortcut = 'all-shortcut-en';
  if (!d[comment_count]) comment_count = 'comment-count';

  gCommentCount = d[comment_count];

  get_category_callback(appid, d[one_app]);
  get_item_callback(appid, d[all_shortcut]);
  get_info_callback(appid, {});
}


function get_page(appid, lang){
  all_data = {};
  all_data_list = [];

  if (!lang) lang = 'cn';
  var u='query.php?op=all&appid='+appid+'&lang='+lang;
  $.ajax({url:u,
      //dataType:"json",
      async:true,
      success : function(msg, textStatus) { 
        gAppID = appid;
        var pos = msg.indexOf('{');
        if (pos >= 0) {
          msg = msg.substring(pos);
        }
        eval('msg='+msg);
        get_all_callback(appid, msg);

        var theme = getInfo(appid, 1);
        var mode = getInfo(appid, 2); // 模式
        change_theme(theme, mode);
      }
  },"text");
}

function change_theme(theme, mode){
  // 确定是否需要载入主题
  var jsname = "./js/theme-"+theme+".js"
  $.getScript(jsname, function(){
    gen_page(gAppID, mode);
    setInfo(gUserID, 1, theme);
    theme_finally();
  }); 

}

function get_apps_callback(appid, m){
  var s = hereDoc(nav_template);
  var r = "";
  for (var i in m) {
    var data = m[i];
    data.name = encodeHtml(data.name);
    data.des = encodeHtml(data.des);
    r += nano(s, data);
  }
  
  r = '<ul class="nav nav-pills ">' + r + '</ul>';
  $("#nav-content").html(r);
}

function get_category_callback(appid, d){
  for (var i in d) {
    var data = d[i];
    $(document).attr("title", data.name+gLangData['lang-shortcut']);//修改title值
    data.name = encodeHtml(data.name);
    //data.des = encodeHtml(data.des);
    data.des = getMarkdown(data.des);
    all_data[data.appid] = {};
    all_data[data.appid].datalist = [];
    all_data[data.appid].info = data;
  }

}

function reorder(d, s) {
  R = [];
  T = [];
  M = {};

  L = new String(s).split(' ');
  for (var i in L) {
    var x = L[i];
    if (d.hasOwnProperty(x)) {
      R.push(x);
      M[x] = 1;
    }
  }

  for (var x in d) {
    if (M.hasOwnProperty(x)) {
      continue;
    } else {
      R.push(x);
    }
  }
  return R;
}

function get_item_callback(appid, d){
  try{
  all_data[appid].datalist = d;
  }catch(e){
  }
}

function get_info_callback(appid, d){
  getInfo(appid, 1);
  getInfo(appid, 2);
  //for (var i in d) {
  //  var k = parseInt(d[i].id);
  //  var v = parseInt(d[i].value);
  //  gInfo[k] = v;
  //}
}


function get_comment_count_callback(appid, d){
  for (var i in d) {
    var data = d[i];
    data.appid = appid;
    var sID = nano("#sns-{appid}-{shortcutid} .count", data);
    var count = data.count;
    $(sID).text(count);
  }
}


function get_str_callback(appid, d){
  for (var i in d) {
    var k = parseInt(d[i].id);
    var v = d[i].value;
    if (!v) v = "";
    gStr[k] = v;
  }
}

//------------------------------------------
//
//
//

function getStr(appid, id) {
  var k = parseInt(id);
  if(gStr[k]){
    return gStr[k];
  }
  return "";
}

function setStr(appid, id, v) {
  var k = parseInt(id);
  v = new String(v).valueOf();
  gStr[k] = v;
  var u = 'update-data.php';
  var data = {
    appid:appid,
    id:k,
    value:v,
    op:"set-str"
  };

  $.post("update-data.php", data,function(msg){
  }); 

  return v;
}

function getInfo(appid, id) {
  var k = parseInt(id);
  if(gInfo[k]){
    return gInfo[k];
  }
  var v = $.cookie(new String(id));
  v = parseInt(v);
  if (v) {
    gInfo[k] = v;
    return v;
  }
  return 0;
}

function setInfo(appid, id, v) {
  var k = parseInt(id);
  v = parseInt(v);
  gInfo[k] = v;
  $.cookie(new String(id), v, 3600*24*7);

  //var u = 'update-data.php';
  //var data = {
  //  appid:appid,
  //  id:k,
  //  value:v,
  //  op:"set-info"
  //};

  //$.post("update-data.php", data,function(msg){
  //}); 

  return v;
}


function gen_page(start, count){
    var u='query.php?op=home-list&start='+start+'&count='+count;
    $.ajax({url:u,
        dataType:"json",
        async:true,
        success : function(msg, textStatus) {
          var data_list = msg['list'];
          var count_list = msg['list-count'];
          var result = "";
          var template_item = hereDoc(item_template);
          var template_column = hereDoc(column_template);
          var COLUMN_COUNT = 6;
          var icol = 0;

            var data_size = data_list.length;
            var content = "";
            var count = 0;

            var count_map = {};
            for(var i in count_list){
              var count_data = count_list[i];
              var k = count_data.id;
              var v = count_data.count;
              count_map[k] = v;
            }

            for(var i in data_list){
              var data=data_list[i]; 
              data.i = count + 1;
              if (count_map[data.id]){
                data.count = count_map[data.id];
              }else{
                data.count = 0;
              }
              var s = nano(template_item, data);
              content += s;
              count += 1;
            }
            
            var next_start = gStart + gCount;
            var prev_start = gStart - gCount;
            if(prev_start < 0) prev_start = 0;
            var data={
              "start":gStart,
              "prev_start":prev_start,
              "next_start":next_start,
              "page":Math.floor(gStart/gCount)+1,
              "count":gCount, 
              "content":content
            };
            result += nano(template_column, data);
            icol += 1;
            if (icol == COLUMN_COUNT) {
              result += '<div class="clearfix"></div>';
              icol = 0;
            }


          $("#result").html(result);

        }
    },"text");
    addListeners();

}

function addListeners(){

  //回车
  $("#autocomplete").unbind('keyup').keyup(function(event){
    if(event.keyCode == 13 || event.keyCode == 10){
      $("#search-go").trigger("click");
    }
  });
  
  //添加搜索
  $("#search-go").unbind('click').click(function(){
    var key =$("#autocomplete").val();
    search_data(key);
  });
  
  //清除结果
  $("#search-clear").unbind('click').click(function(){
    $("#autocomplete").val("");
    $("#search-result").html("");
    $("#autocomplete").focus();
  });
}

/**
 * 生成主页的软件列表
 */
function gen_home_page(){

  var result = ""
  var template_item = hereDoc(app_template);
  var COLUMN_COUNT = 6;
  var count = 0;

  for(var i in gAllApp){
    var data=gAllApp[i];
    data.i = count + 1;
    var s = nano(template_item, data);
    count += 1;

    if (!data.name) data.name = "";
    data.pinyin = hanzi_to_pinyin(data.name).toLowerCase();
    all_data_list.push(data);
    result += s;
  }

  var dataAdd = {
    appid: "0",
    des: "添加新的软件",
    i: 0,
    logo: "http://www.easyicon.net/api/resizeApi.php?id=1187494&size=128",
    name: "Add New",
    pinyin: "Add New",
    skin: "0"
  };
  var s = hereTemplate(add_app_template, dataAdd);
  result=s+result;
  
  $("#result").html(result);

  $(".skin1").addClass("panel-danger");
  $(".skin2").addClass("panel-info");
  $(".skin3").addClass("panel-warning");
  $(".skin4").addClass("panel-success");
  $(".skin5").addClass("panel-default");


  //添加自动提示
  var s = "";
  var arr=[];
  
  $("#autocomplete").autocomplete({
   minLength: 1,
   source:  function(request, response) {
    var result_list = [];
    var key = request.term.toLowerCase();
    for(var i = 0; i < all_data_list.length; i++){
      var data = all_data_list[i];
      if (is_app_matched(key, data)){
          result_list.push(data);
      }
      
      var SHOW_SIZE = 9;
      // 只提示前面的4个
      if (result_list.length > SHOW_SIZE) {
          break;
      }
    }
    response(result_list);
  },
  focus: function(event, ui) {
    $("#autocomplete").val(ui.item.name);
    return false;
  },
  select: function(event, ui) {
    $("#autocomplete").val(ui.item.name);
    return false;
  }
  })
  .autocomplete("instance")._renderItem = function(ul, item) {
    var template = hereDoc(search_app_template);
    return $(nano(template, item))
      .appendTo(ul);
  };

  addListeners();
  
}


var gLang = "cn";
var gAllApp = [];
var gCommentCount = {};
var gUserID = 5012111;
var gAppID = 2;